package item;


import io.Packet;

import java.io.Serializable;
import java.nio.ByteBuffer;

//import org.apache.mina.common.ByteBuffer;

public class BagChangedItem extends ChangedItem implements Serializable{
	
	protected GameItem item;
	protected int count;
	protected BagGrid grid;
	
	public BagChangedItem(BagGrid grid){
		super(TYPE_COMPLEX,BAGGRID,false);
		this.grid = grid;
	}
	
	public BagChangedItem(GameItem item,int count){
		super(TYPE_COMPLEX,ITEM_COUNT_CHANGED,true);
		this.item = item;
		this.count = count;
	}
	
	@Override
	public boolean merge(ChangedItem other){
		if(other instanceof BagChangedItem){
			if(notify==other.notify){
				BagChangedItem o = (BagChangedItem)other;
				if(notify){
					if(item.equals(o.item)){
						count += o.count;
						return true;
					}
					return false;
				}else{
					if(grid.bag.getClass() == o.grid.bag.getClass() && grid.id==o.grid.id && grid.bag.id==o.grid.bag.id){
						grid = o.grid;
						return true;
					}
					return false;
				}
			}else{
				return false;
			}
		}else
			return false;
	}
	
	@Override
	public void pack(Packet pt) {
		if (!notify) 
		{
			pt.put(ChangedItem.TYPE_COMPLEX);
			pt.put(id);
			byte[] bytes = grid.toClientBytes();
			ByteBuffer buffer = ByteBuffer.allocate(bytes.length + 1);
			buffer.put((byte)grid.bag.id);
			buffer.put(bytes);
			pt.put(buffer.array());
		}
		else 
		{
			pt.put(ChangedItem.TYPE_COMPLEX);
			pt.put(id);
			ByteBuffer buffer = ByteBuffer.allocate(10);
			buffer.putInt(item.getTemplate().getId());
			buffer.putInt(item.getInstanceId());
			buffer.putShort((short)count);
			pt.put(buffer.array());
		}
	}
	
	public boolean isBroadcast(){
		return false;
	}
	
	public BagGrid getGrid() {
		return grid;
	}
	
	public void makeBroadcastPacket(Packet pt){
		
	}
}
